package com.wjb.xietong.ota.task;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.wjb.xietong.R;
import com.wjb.xietong.control.WJBControl;
import com.wjb.xietong.datamanager.LoginUserDataManager;
import com.wjb.xietong.datamanager.WJBDataManager;
import com.wjb.xietong.ota.BaseOTA;
import com.wjb.xietong.server.IRequestResultListener;
import com.wjb.xietong.server.myTask.MyTaskParam;
import com.wjb.xietong.server.myTask.MyTaskResponse;
import com.wjb.xietong.server.myTask.MyTaskResponse.MyTaskInfo;
import com.wjb.xietong.server.task.GetTaskParam;
import com.wjb.xietong.server.task.GetTaskResponse;
import com.wjb.xietong.server.task.GetTaskResponse.GetTaskInfo;
import com.wjb.xietong.util.EnumDefine.Delete_Statu;
import com.wjb.xietong.util.EnumDefine.Finish_Statu;
import com.wjb.xietong.util.EnumDefine.Login_User_Info;
import com.wjb.xietong.util.EnumDefine.Task_Type;
import com.wjb.xietong.view.PullToRefreshView;
import com.wjb.xietong.view.PullToRefreshView.OnFooterRefreshListener;
import com.wjb.xietong.view.PullToRefreshView.OnHeaderRefreshListener;

public class OTATask extends BaseOTA implements OnHeaderRefreshListener, OnFooterRefreshListener {

	private final int MESSAGE_FRESH_LISTVIEW = 1;

	private RadioGroup top_radioGroup;

	private int current_index = 0;

	private ListView mListView;
	private ListAdapter mAdapter;

	private List<GetTaskInfo> taskList = new ArrayList<GetTaskInfo>();
	private List<MyTaskInfo> myTaskList = new ArrayList<MyTaskInfo>();

	private boolean isMyTask = false;
	private long projectID = 0l;
	private String projectTitle = "";

	private Button btnAddTask;
	
	private PullToRefreshView mPullToRefreshView;
	private final int PAGE_INDEX = 1;
	private final int NUM_EVERY_PAGE = 50;
	private int mPageIndex = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		mPageIndex = 1;
		Bundle oldBundle = getIntent().getExtras();
		if (oldBundle != null) {
			isMyTask = false;
			projectID = oldBundle.getLong("project_id");
			projectTitle = oldBundle.getString("project_title");
		} else {// 我的任务
			isMyTask = true;
			projectID = -1;
			projectTitle = getString(R.string.STR_TASK_09);
		}
		super.onCreate(savedInstanceState);
		setContentField(getLayoutInflater().inflate(R.layout.page_task, null));
		setTopBarAndAction(projectTitle, new OnClickListener() {

			@Override
			public void onClick(View v) {
				app_.getActManager().popActivity();
			}
		}, null);
	}

	@Override
	protected void findView(View v) {
		super.findView(v);
		mPullToRefreshView = (PullToRefreshView) v.findViewById(R.id.main_pull_refresh_view);
		mPullToRefreshView.setOnHeaderRefreshListener(this, PAGE_INDEX);
		mPullToRefreshView.setOnFooterRefreshListener(this);

		mListView = (ListView) v.findViewById(R.id.id_listview);
		mAdapter = new ListAdapter(OTATask.this);
		mListView.setAdapter(mAdapter);

		btnAddTask = (Button) v.findViewById(R.id.btn_add_task);

		top_radioGroup = (RadioGroup) v.findViewById(R.id.home_radiogroup);
		top_radioGroup
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						switch (checkedId) {
						case R.id.radio1:
							current_index = 0;
							requestTaskList(true, mPageIndex, NUM_EVERY_PAGE);
							break;
						case R.id.radio2:
							current_index = 1;
							requestTaskList(true, mPageIndex, NUM_EVERY_PAGE);
							break;
						case R.id.radio3:
							current_index = 2;
							requestTaskList(true, mPageIndex, NUM_EVERY_PAGE);
							break;
						}
						mListView.setAdapter(null);
					}
				});

		((RadioButton) top_radioGroup.getChildAt(current_index)).toggle();

	}

	@Override
	protected void setOnClickEvent() {
		btnAddTask.setOnClickListener(onClick);
		super.setOnClickEvent();
	}

	private OnClickListener onClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_add_task:
				Intent intent = new Intent(OTATask.this, OTAAddTask.class);
				startActivity(intent);
				break;

			default:
				break;
			}
		}
	};

	Handler handler = new Handler(Looper.getMainLooper()) {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MESSAGE_FRESH_LISTVIEW:
				mListView.setAdapter(new ListAdapter(OTATask.this));
				break;

			default:
				break;
			}
			super.handleMessage(msg);
		}

	};

	/**
	 * 获取任务列表
	 * 
	 * @param type
	 */
	private void requestTaskList(final boolean isRefresh, final int beginRow, final int endRow) {
		showProgressDialog();
		long companyId = (Long) LoginUserDataManager
				.getLoginUserInfo(Login_User_Info.COM_ID);
		long userId = (Long) LoginUserDataManager
				.getLoginUserInfo(Login_User_Info.ID);
		Task_Type type = null;
		if(current_index == 0){
			type = Task_Type.NOT_FINISH;
		}else if(current_index == 1){
			type = Task_Type.FINISH;
		}else{
			type = Task_Type.DELETE;
		}
		
		if (isMyTask) {
			MyTaskParam param = new MyTaskParam();
			param.setCompanyId(companyId);
			param.setUserId(userId);
			param.setPageIndex(beginRow);
			param.setPageSize(endRow);
			switch (type) {
			case DELETE:
				param.setDeleteFlag(Delete_Statu.HAS_DELETE.ordinal());
				break;
			case NOT_FINISH:
				param.setDeleteFlag(Delete_Statu.NOT_DELETE.ordinal());
				param.setOperationStatus(Finish_Statu.NOT_FINISH.ordinal());
				break;
			case FINISH:
				param.setDeleteFlag(Delete_Statu.NOT_DELETE.ordinal());
				param.setOperationStatus(Finish_Statu.HAS_FINISH.ordinal());
				break;
			default:
				break;
			}

			WJBControl.requestGetMyTask(Calendar.getInstance()
					.getTimeInMillis(), param, new IRequestResultListener() {

				@Override
				public void requestSuccess(long requestUniqueID) {
					hideProgressDialog();
					if(isRefresh){
						myTaskList.clear();
					}
					MyTaskResponse myTaskInfo = WJBDataManager
							.getMyTaskResponseInfo();
					if(null != myTaskInfo){
						myTaskList.addAll(myTaskInfo.getMyTaskInfoList());
					}
					handler.sendEmptyMessage(MESSAGE_FRESH_LISTVIEW);
				}

				@Override
				public void requestFaield(long requestUniqueID, String errCode,
						String errMsg) {
					hideProgressDialog();
					Toast.makeText(OTATask.this, (null == errMsg || ""
							.equals(errMsg)) ? "获取任务列表失败" : errMsg, Toast.LENGTH_LONG).show();
				}
			});
		} else {
			GetTaskParam param = new GetTaskParam();
			param.setCompanyId(companyId);
			param.setUserId(userId);
			param.setPageIndex(beginRow);
			param.setPageSize(endRow);
			param.setProjectId(projectID);

			switch (type) {
			case DELETE:
				param.setDeleteFlag(Delete_Statu.HAS_DELETE.ordinal());
				break;
			case NOT_FINISH:
				param.setDeleteFlag(Delete_Statu.NOT_DELETE.ordinal());
				param.setOperationStatus(Finish_Statu.NOT_FINISH.ordinal());
				break;
			case FINISH:
				param.setDeleteFlag(Delete_Statu.NOT_DELETE.ordinal());
				param.setOperationStatus(Finish_Statu.HAS_FINISH.ordinal());
				break;
			default:
				break;
			}
			WJBControl.requestGetTask(Calendar.getInstance().getTimeInMillis(),
					param, new IRequestResultListener() {

						@Override
						public void requestSuccess(long requestUniqueID) {
							hideProgressDialog();
							if(isRefresh){
								taskList.clear();
							}
							GetTaskResponse taskInfo = WJBDataManager
									.getTaskResponseInfo();
							if(null != taskInfo.getGetTaskInfoList()){
								taskList.addAll(taskInfo.getGetTaskInfoList());
							}
							handler.sendEmptyMessage(MESSAGE_FRESH_LISTVIEW);
						}

						@Override
						public void requestFaield(long requestUniqueID,
								String errCode, String errMsg) {
							hideProgressDialog();
							Toast.makeText(OTATask.this, (null == errMsg || ""
									.equals(errMsg)) ? "获取任务列表失败" : errMsg,
									Toast.LENGTH_LONG).show();
						}
					});
		}
	}

	public class ListAdapter extends BaseAdapter {

		private LayoutInflater mInflater;

		public ListAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			if (isMyTask) {
				if (null == myTaskList) {
					return 0;
				}
				return myTaskList.size();
			} else {
				if (taskList == null) {
					return 0;
				}
				return taskList.size();
			}
		}

		@Override
		public Object getItem(int arg0) {
			if (isMyTask) {
				if (null == myTaskList) {
					return null;
				}
				return myTaskList.get(arg0);
			} else {
				if (null == taskList) {
					return null;
				}
				return taskList.get(arg0);
			}
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.item_task_list, null);
				holder = new ViewHolder();
				/* 得到各个控件的对象 */
				holder.iconA = (CheckBox) convertView
						.findViewById(R.id.checkbox_a);
				holder.txtTitle = (TextView) convertView
						.findViewById(R.id.txt_b1);
				holder.txtName = (TextView) convertView
						.findViewById(R.id.txt_b2);
				holder.txtDate = (TextView) convertView
						.findViewById(R.id.txt_b3);

				convertView.setTag(holder); // 绑定ViewHolder对象
			} else {
				holder = (ViewHolder) convertView.getTag(); // 取出ViewHolder对象
			}

			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					Intent intent = new Intent(OTATask.this, OTATaskDetail.class);
					intent.putExtra("cur_tasktab_index", current_index);
					intent.putExtra("from_notice", false);
					intent.putExtra("projectId", projectID);
					intent.putExtra("companyId", (Long) LoginUserDataManager
							.getLoginUserInfo(Login_User_Info.COM_ID));
					if (isMyTask) {
						intent.putExtra("taskId", myTaskList.get(position)
								.getTaskId());
					} else {
						intent.putExtra("taskId", taskList.get(position)
								.getTaskId());
					}
					startActivity(intent);
				}
			});
			if (isMyTask) {
				holder.txtTitle.setText(""
						+ myTaskList.get(position).getTitle());
				holder.txtName.setText(""
						+ (String) LoginUserDataManager
								.getLoginUserInfo(Login_User_Info.USER_NAME));
				holder.txtDate.setText(""
						+ myTaskList.get(position).getDueDate());
			} else {
				holder.txtTitle.setText("" + taskList.get(position).getTitle());
				holder.txtName.setText(""
						+ taskList.get(position).getCurrentOperatorUserName());
				holder.txtDate
						.setText("" + taskList.get(position).getDueDate());
			}
			return convertView;
		}

		/* 存放控件 的ViewHolder */
		public final class ViewHolder {
			public CheckBox iconA;
			public TextView txtTitle;
			public TextView txtName;
			public TextView txtDate;
		}
	}
	
	@Override
	public void onFooterRefresh(PullToRefreshView view, final int pageIndex) {
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				mPullToRefreshView.onFooterRefreshComplete();
				mPageIndex = pageIndex;
				requestTaskList(false, pageIndex, NUM_EVERY_PAGE);
			}
		}, 1000);
	}
	
	@Override
	public void onHeaderRefresh(PullToRefreshView view, final int pageIndex) {
		mPullToRefreshView.postDelayed(new Runnable() {
	
			@Override
			public void run() {
				mPullToRefreshView.onHeaderRefreshComplete();
				mPageIndex = pageIndex;
				requestTaskList(true, pageIndex, NUM_EVERY_PAGE);
			}
		}, 1000);
	}
}
